import { Injectable, Inject, BadRequestException } from '@nestjs/common';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';
import { Repository } from 'typeorm';
import { Task } from './entities/task.entity';

@Injectable()
export class TaskService {
  constructor(
    @Inject('TASK_REPOSITORY')
    private readonly taskRepository: Repository<Task>,
  ) {}

  async create(createTaskDto: CreateTaskDto) {
    let res = undefined;
    try {
      res = await this.taskRepository.insert(createTaskDto);
    } catch (error) {
      throw new BadRequestException('插入任务数据错误：' + error);
    }
    return res;
  }

  async findAll(option: Record<string, any> = null) {
    let res = undefined;
    try {
      if (option === null) {
        res = await this.taskRepository.findAndCount();
      } else {
        res = await this.taskRepository.findAndCount(option);
      }
    } catch (error) {
      throw new BadRequestException('查找任务数据错误:' + error);
    }
    return res;
  }

  async find(option){
    let res = undefined;
    try {
      res = await this.taskRepository.findAndCount(option);
    } catch (error) {
      throw new BadRequestException('查找任务数据错误：' + error);
    }
    return res;
  }

  async findOne(id: number) {
    let res = undefined;
    try {
      res = await this.taskRepository.findOne({ tid: id });
    } catch (error) {
      throw new BadRequestException('查找任务数据错误：' + error);
    }
    return res;
  }

  async update(id: number, updateTaskDto: Partial<UpdateTaskDto>) {
    let res = undefined;
    try {
      res = await this.taskRepository.update({ tid: id }, updateTaskDto);
    } catch (error) {
      throw new BadRequestException('更新任务数据错误：' + error);
    }
    return res;
  }

  async remove(id: number) {
    let res = undefined;
    try {
      res = await this.taskRepository.delete({ tid: id });
    } catch (error) {
      throw new BadRequestException('删除任务数据错误：' + error);
    }
    return res;
  }
}
